﻿using System;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnapptingWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnapptingWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnapptingConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, msg.Reason, channel);
                    }

                    return new ConsumedResult {Ack = true};
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, int reason, WrapperChannel channel)
        {
            string orderNo,orderType;
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var order = ctx.ApptOrders.Where(x => x.Id == orderId)
                    .Select(x => new
                    {
                        x.VisitNo,
                        x.OrderType
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
                orderNo = order.VisitNo;
                orderType = order.OrderType;
            }
          
            //取消预约
            var unApptRequest = new CancelAppointRequest();
            unApptRequest.OrderId = orderNo;
            CancelAppointResponse unApptResponse;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisSp/CancelOrder", unApptRequest).Result;
                responseMsg.EnsureSuccessStatusCode();
                unApptResponse = responseMsg.Content.ReadAsAsync<CancelAppointResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内取消预约Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new ConsumedResult
                {
                    Ack = true
                };
            }

            if (unApptResponse.ResultCode == "0")
            {
                if (reason == 1)
                {
                    DataBaseCommandFactory.CreateDatbaseCommand().CancelByUser(orderId);
                }
                if (reason == 2)
                {
                    DataBaseCommandFactory.CreateDatbaseCommand().CancelBySys(orderId);
                }
                if (reason == 3)
                {
                    DataBaseCommandFactory.CreateDatbaseCommand().CancelByHosp(orderId);
                }

            }

            //if (orderType == ApptOrderExtensions.OrderType.直接挂号.ToInt32().ToString())
            //{
            //    //当天挂号 RMQ 取消锁号
            //    var unlockingProducer = new OrderUnlockingProducer();
            //    unlockingProducer.Publish(new OrderUnlockingMsg
            //    {
            //        OrderType = OrderType.挂号订单,
            //        OrderId = orderId
            //    });
            //}

            return new ConsumedResult
            {
                Ack = true
            };
        }
    }

}
